<?php
namespace App\Http\Controllers\Home;

use App\Models\Member;
use App\Services\Wechat\WechatLogin;

Class IndexController extends BaseController{
    public function __construct(Member $member)
    {
        parent::__construct();
        $this->member = $member;
    }

    /**
     * 游戏首页
     */
//    public function getIndex(){
//        $member = $this->member->getMember($this->mid);
////        dd($member);
//        return view('home.index', compact('member'));
//    }

    public function getIndex(){
        $mid = request('mid');
        $member = $this->member->getMember($mid);
//        dd($member);
        return ajax_return(['status'=>1,'member'=>$member]);
    }
    

    public function getLogin(){
       return view('home.login');
    }

    public function getLogout(){
       $this->member->logout();
        return redirect(action('Home\IndexController@getLogin'));
    }

    public function getTestLogin()
    {
        if(request()->has('openid')) {
            $this->member->wechatLogin(request('openid'));
            return redirect(action('Home\IndexController@getIndex'));
        }
        return view('home.auth');
    }

    public function getTestLogin2()
    {
        if(request()->has('openid')) {
            $res = $this->member->wechatLogin(request('openid'));
            echo json_encode($res);
        }
    }

    public function getOauth2(){
        $appid = '123123';
        $secret = '123123';
        $weixin= new WechatLogin($appid, $secret);
        $code = $_GET['code'];
        if (!isset($code)){
            abort(503, 'NO CODE !');
        }
        $url=$weixin->getCodeUrl($code);
        $res = $weixin->https_request($url);
        $res=(json_decode($res, true));
        if ($res['openid']) {
            $result = $this->member->findMember($res['openid']);
            if (!$result) {
                $wxInfo=$weixin->get_user_info($res['openid']);
            }
            $this->member->wechatLogin($res['openid'], $wxInfo);
            return redirect(action('Home/IndexController@getIndex'));
        }
        abort(503, '授权出错,请重新授权!');
    }


}